import React, { useState } from 'react';
import { Card, DatePicker, Button, Form, Divider, Alert, Spin, Typography, Table } from 'antd';
import { PortfolioAPI } from '../../api/portfolio';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

const PortfolioBacktest = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [result, setResult] = useState(null);

  // 输入的组合，简单写成一只股票，后续可改为动态编辑
  const [portfolioInput, setPortfolioInput] = useState([{ ticker: '000026', weight: 1.0 }]);
  const [dateRange, setDateRange] = useState([null, null]);

  const onDateChange = (dates) => {
    setDateRange(dates);
  };

  const handleBacktest = async () => {
    if (!dateRange[0] || !dateRange[1]) {
      setError('请选择开始和结束日期');
      return;
    }
    setError(null);
    setLoading(true);
    setResult(null);

    try {
      const data = await PortfolioAPI.backtestPortfolio({
        portfolio: portfolioInput,
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
      });
      setResult(data.data);
    } catch (err) {
      setError({
      message: err.response?.data?.message || '请求失败，请稍后重试',
      code: err.response?.data?.code || -1,
    });
    } finally {
      setLoading(false);
    }
  };

  // 简单展示回测结果的表格示例，假设result是一个对象，里面有收益率等字段
  const columns = [
  {
    title: '日期',
    dataIndex: 'date', // 必须和 history 中的 'date' 字段完全一致
    key: 'date',
  },
  {
    title: '总价值',
    dataIndex: 'total_value', // 必须和 history 中的 'total_value' 字段完全一致
    key: 'total_value',
  },
];

  // 根据你的后端回测返回结构，这里做个示例映射
  const tableData = result
    ? Object.entries(result).map(([key, val], idx) => ({
        key: idx,
        metric: key,
        value: typeof val === 'number' ? val.toFixed(4) : val,
      }))
    : [];

  return (
  <div className="backtest-container">
    <Card title="投资组合回测" className="backtest-card">
      <Form layout="vertical">
        <Form.Item label="推荐组合回测">
        <Text>（注意：仅可在30天内回测）</Text>
        </Form.Item>

        <Form.Item label="选择回测时间区间">
          <RangePicker
            onChange={onDateChange}
            disabled={loading}
            allowClear={false}
            format="YYYY-MM-DD"
          />
        </Form.Item>

        {error && <Alert type="error" message={error} showIcon closable onClose={() => setError(null)} />}

        <Form.Item>
          <Button type="primary" onClick={handleBacktest} loading={loading}>
            开始回测
          </Button>
        </Form.Item>
      </Form>

      <Spin spinning={loading} tip="回测中，请稍候...">
        {result && (
          <>
            <Divider />
            <Title level={4}>回测结果</Title>
            
            {/* 回测摘要 */}
            <Card style={{ marginBottom: 16 }}>
              <p>初始资金: ¥{result.initial_capital.toFixed(2)}</p>
              <p>最终价值: ¥{result.final_value.toFixed(2)}</p>
              <p>收益率: {result.return_pct.toFixed(2)}%</p>
            </Card>

            {/* 历史数据表格 */}
            <Table
              columns={columns}
              dataSource={result.history.map((item, index) => ({
                ...item,
                key: index,
                total_value: `¥${item.total_value.toFixed(2)}`,
              }))}
              pagination={false}
              bordered
              size="small"
            />
          </>
        )}
      </Spin>
    </Card>
  </div>
);
};

export default PortfolioBacktest;
